import json

from fastapi import Request, APIRouter, Body, Query
from datetime import datetime, timedelta

from tortoise.queryset import QuerySet

from core.Auth import decode_access_token
from core.Response import success, fail
from core.Utils import process_payment_request, random_str
from models.models import SiteInfo, User, User_vip, Post, PostDteta, Order, Tag
from schemas.posts import SiteInfo_Pydantic, User_Pydantic, Post_Pydantic, AdminPost, admin_Post_Pydantic, \
    Order_Pydantic, PostDteta_Pydantic, Tag_Pydantic

router = APIRouter(prefix='')


@router.get('/user')
async def userinfo(request: Request, page: int = Query(1, ge=1), limit: int = Query(10, ge=1, le=100)):
    headers = request.headers.get("us")
    decoded_data = decode_access_token(headers)

    if decoded_data is None:
        return fail(msg='用户信息错误')

    user = await User.get(id=decoded_data['id'])
    if user.user_type != 1:
        return fail(msg='用户信息错误')

    total = await User.all().count()  # 获取总数
    site_info_items = await User.all().limit(limit).offset((page - 1) * limit)  # 获取分页数据

    # 序列化分页数据
    serialized_items = []
    for item in site_info_items:
        user = User_Pydantic.from_orm(item).dict()
        print()
        uservip = await User_vip.get_or_none(user=item)
        if uservip is not None:
            user.update({'vip_type': uservip.vip_type, 'vip_status': uservip.vip_status})
        else:
            user.update({'vip_type': None, 'vip_status': False})  # 或者其他默认值

        serialized_items.append(user)
    # user_vip = await User_vip.all()
    print(serialized_items)
    # 构造响应数据
    response_data = {
        "total": total,
        "page": page,
        "limit": limit,
        "data": serialized_items,
    }

    return success(data=response_data)


@router.post('/articles/')
async def user_articles(request: Request, user_data: dict = Body(...)):
    headers = request.headers.get("us")
    decoded_data = decode_access_token(headers)

    if decoded_data is None:
        return fail(msg='用户信息错误')

    user = await User.get(id=decoded_data['id'])
    if user.user_type != 1:
        return fail(msg='用户信息错误')

    print(user_data)
    user_id = user_data.pop('id')
    user_articles = await User.get(id=user_id)
    key = next(iter(user_data))
    value = user_data[key]

    if key in ['vip_status', 'vip_type']:
        uservip, created = await User_vip.get_or_create(user=user_articles,
                                                        defaults={'vip_type': 0, 'vip_status': False})
        if uservip is not None:
            setattr(uservip, key, value)  # 动态设置属性
            await uservip.save()  # 保存更改

    setattr(user_articles, key, value)  # 动态设置属性
    await user_articles.save()  # 保存更改

    return success(data=[], msg='修改成功')


@router.delete('/user/{id}')
async def delete_user(request: Request, id: int):
    headers = request.headers.get("us")
    decoded_data = decode_access_token(headers)

    if decoded_data is None:
        return fail(msg='用户信息错误')

    user = await User.get(id=decoded_data['id'])
    if user.user_type != 1:
        return fail(msg='用户信息错误')
    if user.id == id:
        return fail(msg='不能删除自己')
    user_articles = await User.get(id=id)
    await user_articles.delete()

    return success(data=[], msg='删除成功')


@router.get('/posts')
async def posts(request: Request, page: int = Query(1, ge=1), limit: int = Query(10, ge=1, le=100)):
    headers = request.headers.get("us")
    decoded_data = decode_access_token(headers)

    if decoded_data is None:
        return fail(msg='用户信息错误')

    user = await User.get(id=decoded_data['id'])
    if user.user_type != 1:
        return fail(msg='用户信息错误')

    total = await Post.all().count()  # 获取总数
    post_items = await Post.all().limit(limit).offset((page - 1) * limit)  # 获取分页数据

    # 序列化分页数据
    serialized_items = []
    for item in post_items:
        post = admin_Post_Pydantic.from_orm(item).dict()
        print(item)
        if isinstance(item.post_detail, QuerySet):
            post_detail_instance = await item.post_detail.first()  # 获取第一个实例
            if post_detail_instance:
                post_detail = await PostDteta.get(id=post_detail_instance.id)
            else:
                # 处理没有找到实例的情况
                post_detail = None
        else:
            post_detail = await PostDteta.get(id=item.post_detail)
        # 使用点访问法而不是字典访问
        if hasattr(post_detail, 'imageSrc') and isinstance(post_detail.imageSrc, list):
            post_detail.imageSrc = len(post_detail.imageSrc)  # 设置为列表的长度
        else:
            print("imageSrc 属性不存在或不是列表")

        post.update(post_detail)

        print(post)

        serialized_items.append(post)

    # 构造响应数据
    response_data = {
        "total": total,
        "page": page,
        "limit": limit,
        "data": serialized_items,
    }

    return success(data=response_data)


@router.post('/revisepost/')
async def user_articles(request: Request, user_data: dict = Body(...)):
    print(user_data)
    headers = request.headers.get("us")
    decoded_data = decode_access_token(headers)

    if decoded_data is None:
        return fail(msg='用户信息错误')

    user = await User.get(id=decoded_data['id'])
    if user.user_type != 1:
        return fail(msg='用户信息错误')

    # 从 user_data 中移除 'id' 并获取要更新的帖子 ID
    post_id = user_data.pop('id')

    # 根据 ID 获取当前文章
    post_articles = await Post.get(id=post_id)

    if post_articles is None:
        return fail(msg='文章不存在')

    istop = await Post.all().filter(isTop=True).count()  # 仅计算 isTop 为 True 的文章数量

    # 迭代 user_data 中的键值对更新文章属性
    for key, value in user_data.items():  # 使用 items() 遍历键值对
        if istop > 4 and value is True and key == 'isTop':
            return fail(msg='置顶次数已达上限,请将其他文章取消置顶后再尝试置顶！')

        # 检查 Post_articles 是否有此属性
        if hasattr(post_articles, key):
            setattr(post_articles, key, value)  # 设置属性
        else:
            # 如果没有此属性，尝试查找 PostDteta 表
            post_detail = await PostDteta.get_or_none(id=post_id)
            if post_detail and hasattr(post_detail, key):
                setattr(post_detail, key, value)  # 设置属性
            else:
                print(f"Field {key} not found in Post or PostDteta records")
                return fail(msg=f'字段 {key} 无效或不存在')

    # 保存更改到数据库
    await post_articles.save()

    # 如果在 PostDteta 表中进行了更新，则也保存
    if post_detail:
        await post_detail.save()

    return success(data=[], msg='修改成功')


@router.delete('/posts/{id}')
async def delete_post(request: Request, id: int):
    headers = request.headers.get("us")
    decoded_data = decode_access_token(headers)

    if decoded_data is None:
        return fail(msg='用户信息错误')

    user = await User.get(id=decoded_data['id'])
    if user.user_type != 1:
        return fail(msg='用户信息错误')

    post_articles = await Post.get(id=id)

    pdeta = await PostDteta.get(id=post_articles.post_detail)
    await pdeta.delete()
    await post_articles.delete()

    return success(data=[], msg='删除成功')


@router.get('/search')
async def search_posts(request: Request, title: str = Query(None), ):
    print(title, 111111)
    if title is None:
        return fail(msg='搜索内容不能为空')
    headers = request.headers.get("us")
    decoded_data = decode_access_token(headers)

    if decoded_data is None:
        return fail(msg='用户信息错误')

    user = await User.get(id=decoded_data['id'])
    if user.user_type != 1:
        return fail(msg='用户信息错误')
    search_result = await Post.filter(title__icontains=title).all()
    serialized_items = []
    for item in search_result:
        post = admin_Post_Pydantic.from_orm(item).dict()
        serialized_items.append(post)
    data = {
        "data": serialized_items,
        "total": len(serialized_items)
    }

    return success(data=data, msg='搜索成功')


@router.get('/pricing')
async def pricing(request: Request):
    headers = request.headers.get("us")
    decoded_data = decode_access_token(headers)

    if decoded_data is None:
        return fail(msg='用户信息错误')

    user = await User.get(id=decoded_data['id'])
    if user.user_type != 1:
        return fail(msg='用户信息错误')
    pic = await Order.all()
    serialized_items = []
    for item in pic:
        post = Order_Pydantic.from_orm(item).dict()
        serialized_items.append(post)

    return success(data=serialized_items, msg='')


@router.put('/pricing/{id}')
async def pricing_update(request: Request, id: int, data: dict = Body(...)):
    headers = request.headers.get("us")
    decoded_data = decode_access_token(headers)

    if decoded_data is None:
        return fail(msg='用户信息错误')

    user = await User.get(id=decoded_data['id'])
    if user.user_type != 1:
        return fail(msg='用户信息错误')
    order = await Order.get(id=id)
    key = next(iter(data))
    value = data[key]
    setattr(order, key, value)  # 动态设置属性
    await order.save()  # 保存更改
    return success(data=[], msg='修改成功')


@router.delete('/pricing/{id}')
async def pricing_delete(request: Request, id: int):
    headers = request.headers.get("us")
    decoded_data = decode_access_token(headers)
    if decoded_data is None:
        return fail(msg='用户信息错误')
    user = await User.get(id=decoded_data['id'])
    if user.user_type != 1:
        return fail(msg='用户信息错误')
    order = await Order.get(id=id)
    await order.delete()
    return success(data=[], msg='删除成功')

@router.get('/tags')
async def tags(request: Request, ):
    headers = request.headers.get("us")
    decoded_data = decode_access_token(headers)
    if decoded_data is None:
        return fail(msg='用户信息错误')
    user = await User.get(id=decoded_data['id'])
    if user.user_type != 1:
        return fail(msg='用户信息错误')
    tags =await Tag.all()
    serialized_items = []
    for item in tags:
        post = Tag_Pydantic.from_orm(item).dict()
        serialized_items.append(post)
    return success(data=serialized_items, msg='')
@router.put('/tags/{id}')
async def addtag(request: Request,id: int, data: dict = Body(...)):
    headers = request.headers.get("us")
    decoded_data = decode_access_token(headers)
    if decoded_data is None:
        return fail(msg='用户信息错误')
    user = await User.get(id=decoded_data['id'])
    if user.user_type != 1:
        return fail(msg='用户信息错误')
    tag = await Tag.get(id=id)
    key = next(iter(data))
    value = data[key]
    setattr(tag, key, value)  # 动态设置属性
    await tag.save()
    return success(data=[], msg='修改成功')

@router.delete('/tags/{id}')
async def delete_tag(request: Request, id: int):
    headers = request.headers.get("us")
    decoded_data = decode_access_token(headers)
    if decoded_data is None:
        return fail(msg='用户信息错误')
    user = await User.get(id=decoded_data['id'])
    if user.user_type != 1:
        return fail(msg='用户信息错误')
    tag = await Tag.get(id=id)
    await tag.delete()
    return success(data=[], msg='删除成功')

